// import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:nmb/models/fold.dart';
import '../models/note.dart';
import '../screens/note_detail.dart';
import '../services/global.dart';
import 'folder_manage.dart';
import 'package:timeago/timeago.dart' as timeago;

class NotesListScreen extends StatefulWidget {
  const NotesListScreen({super.key});

  @override
  _NotesListScreenState createState() => _NotesListScreenState();
}

class _NotesListScreenState extends State<NotesListScreen> {
  late List<Note> notes;
  late List<Note> list;
  late List<Fold> foldList;
  final TextEditingController _searchController = TextEditingController();
  String _searchQuery = '';

  final ValueNotifier<String> _selectedFold = ValueNotifier('');

  final ValueNotifier<bool> _showSearch =ValueNotifier(false);

  final service = Get.find<GlobalService>();

  @override
  void initState() {
    super.initState();
    list = [];
    foldList = service.foldList;
    _searchController.addListener(() {
      setState(() {
        _searchQuery = _searchController.text;
        list = service.noteList.where((e)=>e.content.contains(_searchQuery)||e.title.contains(_searchQuery)).toList();
      });
    });
    service.noteChanged.addListener((){
      setState(() {
        list = service.noteList;
      });
    });
    service.folderChanged.addListener((){
      setState(() {
        foldList = service.foldList;
      });
    });
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  void _toggleSearch(){
    _showSearch.value = !_showSearch.value;
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('记事本',style: TextStyle(
          color: Colors.white
        ),),
        actions: [
          IconButton(onPressed: (){
            Get.to( FolderManage());
          }, icon: Icon(Icons.folder)),
          IconButton(
            icon: const Icon(Icons.search_rounded),
            onPressed: _toggleSearch,
          ),
        ],
        backgroundColor: Colors.black,
        foregroundColor: Colors.white,
      ),
      backgroundColor: Colors.black,
      body: Column(
        children: [
          ValueListenableBuilder(valueListenable: _showSearch , builder: (context, show, child){
            if(show){
              return Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    margin: const EdgeInsets.all(16.0),
                    padding: EdgeInsets.symmetric(vertical: 4),
                    decoration: BoxDecoration(
                      color: Color(0xff1f1f1f),
                      borderRadius: BorderRadius.circular(36)
                    ),
                    child: TextField(
                      controller: _searchController,
                      decoration: InputDecoration(
                        prefixIcon: const Icon(Icons.search,color: Color(0xff8c8c8c),),
                        border: InputBorder.none,
                        hintText: '搜素笔记',
                        hintStyle: TextStyle(
                          color: Color(0xff5f5f5f)
                        )
                      ),
                      style: TextStyle(
                        color: Color(0xff5f5f5f)
                      ),
                    ),
                  ),
                  Container(
                    height:64,
                    margin: const EdgeInsets.symmetric(horizontal: 16.0),
                    child: ListView.builder(
                        itemBuilder: (context,index){
                      final fold = foldList[index];
                      return GestureDetector(
                        onTap: (){
                          setState(() {
                            _selectedFold.value = fold.id;
                            if(_selectedFold.value.isEmpty){
                              list = service.noteList;
                            }else{
                              list = service.noteList.where((e)=>e.foldId==_selectedFold.value).toList();
                            }
                          });
                        },
                        child: Container(
                          padding: EdgeInsets.all(16),
                          margin: EdgeInsets.only(bottom: 8,right: 8),
                          decoration: BoxDecoration(
                            color: Color(0xff242424),
                            borderRadius: BorderRadius.circular(16),
                          ),
                          child: Text(fold.name,style: TextStyle(
                              color: Colors.white,
                              fontSize: _selectedFold.value == fold.id ? 16:14,
                              fontWeight: _selectedFold.value == fold.id ? FontWeight.bold : FontWeight.normal
                          ),),
                        ),
                      );
                    },itemCount: foldList.length,scrollDirection: Axis.horizontal,),
                  )
                ],
              );
            }
            return SizedBox();
          }),
          Expanded(
            child: ValueListenableBuilder(valueListenable: service.noteChanged, builder: (context,changed,child){
              if(list.isEmpty){
                return Center(
                  child: Text('暂无数据',style: TextStyle(
                    color: Colors.white70
                  ),),
                );
              }
              return ListView.builder(
                itemCount: list.length,
                itemBuilder: (context, index) {
                  final note = list[index];
                  return Container(
                    margin: EdgeInsets.only(left: 16.0,right: 16,bottom: 16),
                    decoration: BoxDecoration(
                        color: Color(0xff242424),
                        borderRadius: BorderRadius.circular(16.0)
                    ),
                    child: ListTile(
                      title: Text(note.title,style: TextStyle(
                          color: Colors.white,
                          fontSize: 22,
                          fontWeight: FontWeight.bold
                      ),),
                      subtitle: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            note.content.length > 36
                                ? '${note.content.substring(0, 36)}...'
                                : note.content,
                            style: TextStyle(
                                fontSize: 16,
                                color: Color(0xff939393)
                            ),
                          ),
                          Text(
                            note.dateModified != null
                                ? timeago.format(note.dateModified!,locale: 'zh_CN')
                                : timeago.format(note.dateCreated,locale: 'zh_CN'),
                            style: const TextStyle(fontSize: 14,color: Color(0xff939393)),
                          ),
                        ],
                      ),
                      onTap: () {
                        Get.to(NoteDetailScreen(noteId: note.id!));
                      },
                    ),
                  );
                },
              );
            }),
          )]),
      floatingActionButton: FloatingActionButton(
        shape: CircleBorder(),
        backgroundColor: Color(0xFFeca201),
        child: const Icon(Icons.add,color: Colors.white70,),
        onPressed: () {
          Get.to(const NoteDetailScreen());
        },
      ),
    );
  }
}